from threading import Thread,Condition,Lock
from cv2 import VideoCapture,resize,rectangle,imshow,waitKey,cvtColor,flip,CAP_PROP_FPS, \
                                    CAP_PROP_CONVERT_RGB,CAP_GSTREAMER,INTER_AREA,COLOR_BGR2RGB, \
                                    copyMakeBorder,BORDER_CONSTANT,destroyWindow,imwrite,IMWRITE_JPEG_QUALITY
import numpy as np
from  collections import deque
from time import sleep

class Camera(Thread):
    def __init__(self,dev,width,height):
        Thread.__init__(self)
        self.__locker=Lock()
        self.__runing_flag=True
        self.__not_empty=Condition(self.__locker)
        self.__not_full=Condition(self.__locker)
        self.__buf=deque()
        gst_str = ('v4l2src device=/dev/video{} ! '
               'video/x-raw, width=(int){}, height=(int){} ! '
               'videoconvert ! appsink').format(dev, width, height)
        self.__cap=VideoCapture(gst_str,CAP_GSTREAMER)
        #self.__cap=VideoCapture("/home/shuaihu/07.mp4")
        #self.__cap.set(CAP_PROP_CONVERT_RGB,1)

    def open(self):
        self.start()
    def __runing(self):
        with self.__locker:
            return self.__runing_flag
    def __push(self,img1,img2):
        with self.__not_full:
            while len(self.__buf):
                self.__not_full.wait()
            self.__buf.append(img1)
            self.__buf.append(img2)
            self.__not_empty.notify()
    def stop(self):
        with self.__locker:
            self.__runing_flag=False
            self.__buf.clear()
            self.__not_full.notify()
        self.join()
    def read(self):
        with self.__not_empty:
            while not  len(self.__buf):
                self.__not_empty.wait()
            img=self.__buf.popleft()
            img1=self.__buf.popleft()
            self.__not_full.notify()
            return img,img1
    def run(self):        
        while self.__runing():
            _,img=self.__cap.read()
            smg=resize(img,(300,225),interpolation=INTER_AREA )
            #smg=flip(smg,1)
            bod=copyMakeBorder(smg,37,38,0,0,BORDER_CONSTANT,value=(255,255,255))
            rgbimg =cvtColor(bod, COLOR_BGR2RGB)
            timg=rgbimg.transpose((2, 0, 1)).astype(np.float32)
            timg=(1.0/255.0)*timg
            self.__push(timg,img)
        self.__cap.release()
        self.__cap=None


            
